package org.catspaw.cherubim.persistence.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import org.catspaw.cherubim.persistence.PersistenceException;
import org.catspaw.cherubim.persistence.transaction.TransactionManager;

public class HibernateTransactionManager implements TransactionManager {

	public void beginTransaction() throws PersistenceException {
		Session session = SessionManager.getInstance().getSession();
		try {
			session.beginTransaction();
		} catch (HibernateException e) {
			throw new PersistenceException(e);
		}
	}

	public boolean inTransaction() throws PersistenceException {
		Session session = SessionManager.getInstance().getCurrentSession();
		try {
			if (session != null && session.getTransaction().isActive()) {
				return true;
			}
		} catch (HibernateException e) {
			throw new PersistenceException(e);
		}
		return false;
	}

	public void commit() throws PersistenceException {
		Session session = SessionManager.getInstance().getCurrentSession();
		if (session == null) {
			throw new IllegalStateException("current thread is no hibernate session in transaction");
		}
		try {
			session.getTransaction().commit();
		} catch (HibernateException e) {
			throw new PersistenceException(e);
		}
	}

	public void rollback() throws PersistenceException {
		Session session = SessionManager.getInstance().getCurrentSession();
		if (session == null) {
			throw new IllegalStateException("current thread is no hibernate session in transaction");
		}
		try {
			session.getTransaction().rollback();
		} catch (HibernateException e) {
			throw new PersistenceException(e);
		}
	}
}
